import { defineConfig, loadEnv } from "vite";
import { fileURLToPath } from "url";
import path from "path";
import { Plugin as importToCDN } from "vite-plugin-cdn-import";
import vue from "@vitejs/plugin-vue";
import { dirname, resolve } from "node:path";
import { globSync } from "glob";
import fs from "fs";

const __dirname = dirname(fileURLToPath(import.meta.url));

export default defineConfig(({ command, mode }) => {
    const env = loadEnv(mode, process.cwd(), "");

    return {
        define: {
            __APP_ENV__: JSON.stringify(env.APP_ENV),
        },
        plugins: [
            {
                name: 'write-version-plugin',
                closeBundle() {
                    const version = env.VITE_THEME_VERSION;
                    const yamlFilePath = path.resolve(__dirname, 'theme.yaml');
                    let yamlContent = fs.readFileSync(yamlFilePath, 'utf8');
                    yamlContent = yamlContent.replace(/version:\s*.*$/m, `version: ${version}`);
                    fs.writeFileSync(yamlFilePath, yamlContent, 'utf8');
                },
            }
        ],
        manifest: true,
        root: resolve(__dirname, 'src/pages/'),
        base: 'src/',
        publicDir: resolve(__dirname, 'src/public'),
        build: {
            emptyOutDir: true,
            outDir: resolve(__dirname, 'templates'),
            assetsDir: resolve(__dirname, 'assets'),
            rollupOptions: {
                watch: {
                    include: ['src'],
                },
                input: Object.fromEntries(
                    globSync(["src/main.ts", "src/libs/**/*.*", "src/pages/**/*.*"]).map((file) => {
                        return [
                            path.parse(path.basename(file)).name,
                            fileURLToPath(new URL(file, import.meta.url)),
                        ]
                    })
                ),
                output: {
                    format: "es",
                    entryFileNames: `assets/dist/js/[name]-${env.VITE_THEME_VERSION}.min.js`,
                    assetFileNames: (assetInfo) => {
                        if (assetInfo.name && assetInfo.name.endsWith(".css")) {
                            return `assets/dist/css/[name]-${env.VITE_THEME_VERSION}.min.[ext]`;
                        }
                        return `[name].min.[ext]`;
                    },
                },
            },
            minify: mode === "development" ? false : true,
            sourcemap: mode === "development" ? false : false,
            chunkSizeWarningLimit: 1024,
            watch: {

            }
        },
    };
});
